package handler

import (
	"car-trade-mgr/cache"
	"car-trade-mgr/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarCarTypeList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var CarCarType []model.CarCarType
	/*
		SELECT
		  car_types.id as CarCarTypeId,
		  car1.car_name as CarName,
		  car1.car_type as CarType,
		  car1.car_price as CarPrice,
		  car1.car_time as CarTime,
		  car_types.type_name as TypeName,
		  car_types.car_comment as CarComment,
		  car_types.car_num as CarNum
		FROM
		  car_types
		  LEFT JOIN car1 ON car1.id = car_types.cid
	*/
	redis_key := "car_carType_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_types").Select(
			"car_types.id as CarCarTypeId",
			"car1.car_name as CarName",
			"car1.car_type as CarType",
			"car1.car_price as CarPrice",
			"car1.car_time as CarTime",
			"car_types.type_name as TypeName",
			"car_types.car_comment as CarComment",
			"car_types.car_num as CarNum",
		).Joins("LEFT JOIN car1 ON car1.id = car_types.cid").
			Offset(offset).Limit(size).Find(&CarCarType).Debug()
		jsonData, _ := json.Marshal(CarCarType)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &CarCarType)
	}
	var total int64
	model.DB.Model(&model.CarType{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": CarCarType,
	})
	return
}
func CarCarTypeDetail(c *gin.Context) {
	id := c.Query("id")
	var CarCarType model.CarCarType
	/*
			SELECT
			  car_types.id as CarCarTypeId,
			  car1.car_name as CarName,
			  car1.car_type as CarType,
			  car1.car_price as CarPrice,
			  car1.car_time as CarTime,
			  car_types.type_name as TypeName,
			  car_types.car_comment as CarComment,
			  car_types.car_num as CarNum
			FROM
			  car_types
			  LEFT JOIN car1 ON car1.id = car_types.cid
		 WHERE car1.id=1
	*/
	redisKey := "car_carType_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redisKey).Result()
	if cacheData == "" {
		model.DB.Table("car_types").Select(
			"car_types.id as CarCarTypeId",
			"car1.car_name as CarName",
			"car1.car_type as CarType",
			"car1.car_price as CarPrice",
			"car1.car_time as CarTime",
			"car_types.type_name as TypeName",
			"car_types.car_comment as CarComment",
			"car_types.car_num as CarNum",
		).Joins("LEFT JOIN car1 ON car1.id = car_types.cid").
			Where("car1.id=?", id).Find(&CarCarType).Debug()
		jsonData, _ := json.Marshal(CarCarType)
		cache.Rdb.Set(cache.Ctx, redisKey, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &CarCarType)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": CarCarType,
	})
	return
}
